package com.offcn.seckill.service.impl;

import com.offcn.entity.StatusCode;
import com.offcn.seckill.dao.SeckillGoodsMapper;
import com.offcn.seckill.dao.SeckillOrderMapper;
import com.offcn.seckill.pojo.SeckillGoods;
import com.offcn.seckill.pojo.SeckillOrder;
import com.offcn.seckill.service.SeckillOrderService;
import com.offcn.entity.PageResult;
import com.offcn.seckill.thread.MultiTreadeCreateOrder;
import com.offcn.seckill.thread.SecKillOrderStatus;
import com.offcn.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Date;
import java.util.List;

/****
 * @Author:ujiuye
 * @Description:SeckillOrder业务层接口实现类
 * @Date 2021/2/1 14:19
 *****/
@Service
public class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderMapper, SeckillOrder> implements SeckillOrderService {




    @Autowired
    private MultiTreadeCreateOrder multiTreadeCreateOrder;

    @Autowired
    private RedisTemplate redisTemplate;

    //超卖 id=1000 有两个2  goodCount_1000 给队列中放入两个商品
    /**
     * 添加 秒杀 订单
     */
    @Override
    public Boolean add(Long id, String time, String username) {

        //给用户抢单 进行赋值 自增值 1
        Long queueStatus = redisTemplate.boundHashOps("UserQueueStatus").increment(username, 1);
        if (queueStatus>1){
            //不允许 用户 重复抢单
            throw  new RuntimeException(String.valueOf(StatusCode.PREERROR));
        }

        //封装排队信息
        SecKillOrderStatus status = new SecKillOrderStatus(username, new Date(), 1, id, time);

        //将秒杀 抢单信息 存储到redis List
        redisTemplate.boundListOps("SeckillOrderQueue").leftPush(status);

        //将单独状态存入redis
        redisTemplate.boundHashOps("UserQueueStatus").put(username,status);

        multiTreadeCreateOrder.createOrder();
        return true;
    }

    /**
     * 抢单 状态查询方法
     */
    @Override
    public SecKillOrderStatus queryStatus(String username) {

        return (SecKillOrderStatus) redisTemplate.boundHashOps("UserQueueStatus").get(username);
    }


}
